package com.big_data_studio.aop;

import com.big_data_studio.util.general.R;
import com.big_data_studio.util.general.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author xiao_jie
 * @date 2022/10/16 16:37
 * @describe 设置切入点，拦截请求详情页面的接口请求，从而让redis实时更新浏览量
 */


// 定义该类为切面类
@Aspect
@Component
@Slf4j
public class StarAop {

    @Autowired
    private RedisUtil redisUtil;

    //  execution()语法：execution(修饰符  返回值  包.类.方法名(参数) throws异常)  .. 表示任意参数
    @Pointcut("execution(public * com.big_data_studio.controller.*.getOne(..))")
    public void starAopCut() {
    }

    ;

    /**
     * 前置操作，判断该接口的浏览量是否存入redis
     *
     * @param joinPoint
     */
    @Before("starAopCut()")
    public void StarBefore(JoinPoint joinPoint) {
        String simpleName = joinPoint.getSignature().getDeclaringType().getSimpleName();
        String keyName = simpleName.replace("Controller", "");
        Object[] args = joinPoint.getArgs();
        Integer id = (Integer) args[0];
        boolean b = redisUtil.hHasKey(keyName, id.toString());
        if (!b) {
            redisUtil.hset(keyName, id.toString(), 1);
        }
    }


    /**
     * 在getOne方法返回结果后执行,获取key,浏览量+1
     *
     * @param joinPoint
     * @param result
     */
    @AfterReturning(value = "starAopCut()", returning = "result")
    public void StarAfter(JoinPoint joinPoint, R result) {
        // 获取实体类名字-----即redis的key
        String keyName = result.getData().getClass().getSimpleName();
        System.out.println(keyName);
        Object[] args = joinPoint.getArgs();
        Integer id = (Integer) args[0];
        // 根据id更新浏览量,每次+1
        try {
            redisUtil.hincr(keyName, id.toString(), 1);
        } catch (Exception e) {
            System.out.println("添加失败异常");
            e.printStackTrace();
        }
    }


}
